import utils from '../../../utils/utils.js'
import Dialog from '../../../dist/dialog/dialog';
import { couponGoodsMap } from '../../../utils/dataMap.js'
import { HomeHttp } from '../../../api/home.js'
const homeModel = new HomeHttp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    searchVal: '', // 搜素值
    searchResult: [], // 搜索结果
    searchHistoryList: [], // 搜索历史
    isShowSearchResult: false, // 是否显示搜索结果
    historyPage: 1,
    historyPageSize: 10,
    historyTotalNum: 0
  },

  initPage () {
    this.httpSearchCouponHistory()
  },

  // 搜券输入框 - 值改变回到事件
  onSearchFieldChange (event) {
    this.setData({
      searchVal: event.detail
    })
  },

  // 搜券
  onSearchCoupon () {
    const { searchVal } = this.data
    if (searchVal === '') {
      utils.msg('请输入商品链接')
      this.setData({
        searchResult: [],
        isShowSearchResult: false,
        historyPage: 1
      })
      this.httpSearchCouponHistory()
      return
    }
    homeModel.searchPlatformGoodsCoupon({
      link: this.data.searchVal
    }).then(res => {
      let resMap = couponGoodsMap(res.goods_list)
      this.setData({
        searchResult: resMap,
        isShowSearchResult: true
      })
      // 完成搜券新手任务
      homeModel.completeNewTask({
        type: 'search'
      })
    })
  },

  // 清空搜索
  onClearSearch () {
    this.setData({
      searchVal: ''
    })
  },

  // 删除搜券历史
  deleteCouponHistory () {
    console.log('删除搜券历史')
    Dialog.confirm({
      message: '是否删除搜索历史？'
    }).then(() => {
      homeModel.deleteSearchCouponHistory().then(res => {
        this.setData({
          searchHistoryList: []
        })
        utils.msg('删除成功！')
      })
    }).catch(() => {
      // on cancel
    });
  },

  // 页面上拉触底事件的处理函数
  onReachBottom: function () {
    const { searchHistoryList, historyTotalNum } = this.data
    if (searchHistoryList.length < historyTotalNum) {
      this.setData({
        historyPage: this.data.historyPage + 1
      })
      this.httpSearchCouponHistory()
    }
  },

  httpSearchCouponHistory () {
    const { historyPage, historyPageSize } = this.data
    return homeModel.searchPlatformCouponHistory({
      page: historyPage, // 页数
      page_size: historyPageSize // 每页数量
    }).then(res => {
      let resMap = couponGoodsMap(res.goods_list)
      this.setData({
        searchHistoryList: resMap,
        historyTotalNum: res.total_count
      })
    })
  },
});
